9. Developer Resources • Google Code Website • http://code.google.com/ • Code Playground • http://code.google.com/apis/ajax/playground/ • Firefox & Firebug • http://moztw.org/ • Google Code Blog • http://googlecode.blogspot.com/
10. Some Interesting APIs #1 • Google Account Authentication ‧ Get access into desktop or mobile applications. • Google AJAX Feed API ‧ Get access into desktop or mobile applications. • Google AJAX Language API ‧ Easily translate and detect multiple languages using JavaScript. • Android ‧ Build mobile apps for mobile devices. • Google App Engine ‧ Run your web applications on Google's infrastructure. • Google Apps ‧ Extend Google Apps, integrate or build new apps. • Blogger Data API ‧ Enable your apps to view and update Blogger content.
11. Some Interesting APIs #2 • Google Calendar APIs and Tools ‧ Create and manage events, calendars • Google Chrome Extensions ‧ Modify and enhance the functionality of Google Chrome • Google Earth API ‧ Embed Google Earth into your web page. • KML ‧ Create and share content with Google Earth, Maps • Google Libraries API ‧ Load open source JavaScript libraries. • reCAPTCHA ‧ An anti-bot service. • YouTube APIs ‧ Integrate YouTube videos into your website or application.
14. Google AJAX Search API Intro • The Google AJAX Search API lets you put Google Search in your web pages with JavaScript. • Getting Start ‧ Get Google AJAX Search API Key and start coding ‧ Or Generate cut-and-paste HTML, it’s an easy way • Web Resources ‧ http://code.google.com/apis/ajaxsearch/ ‧ http://groups-beta.google.com/group/Google-AJAX-Search-API ‧ http://code.google.com/apis/ajaxsearch/samples.html
15. Google AJAX Search API Wizards #1 • http://code.google.com/apis/ajaxsearch/wizards.html
16. Google AJAX Search API Wizards #2 • For Example : Video Search Wizard • http://www.google.com/uds/solutions/wizards/videosearch.html • Only 4 Steps • Customize it • Tell Google about your web site • Generate code for your web page • Paste code in your web page
18. "Hello World" of Google AJAX Search API #2 • The "Hello, World" of Google AJAX Search API • Sample Code • http://www.google.com/uds/samples/apidocs/helloworld.html • Using the Google AJAX API Loader <script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script> <script type="text/javascript"> google.load("search", "1"); </script>
19. "Hello World" of Google AJAX Search API #3 • Call this function when the page has been loaded function initialize() { var searchControl = new google.search.SearchControl(); searchControl.addSearcher(new google.search.WebSearch()); searchControl.addSearcher(new google.search.NewsSearch()); searchControl.draw(document.getElementById("searchcontrol")); } • Execute Search function searchControl.execute("VW GTI"); • Use google.setOnLoadCallback to register the specified handler function google.setOnLoadCallback (initialize); • Put <div> in HTML <div id="searchcontrol">Loading</div>
20.
21. Google AJAX Search API Overview #sample code1 // create a searcher object var sc = new google.search.SearchControl(); // add one or more searchers, specifying options as needed var options = new google.search.SearcherOptions(); options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN); sc.addSearcher(new google.search.WebSearch(), options); ... // activate the search control by calling it's .draw() method sc.draw(document.getElementById("myDiv"));
22. Google AJAX Search API Overview #sample code2 <!-- A collection of web search results in the search control --> <div class="gsc-results gsc-webResult"> <!-- A single web result in the search control --> <div class="gsc-result gsc-webResult"> <!-- A single web result, full structure defined below --> <div class="gs-result gs-webResult"></div> </div> ... </div> <!-- Similar pattern for local, blog, etc. --> <div class="gsc-results gsc-localResult"></div> <div class="gsc-results gsc-blogResult"></div>
24. google.search.SearchControl #1 • An instance of google.search.SearchControl represents a single search control on a page • 是用來裝載搜尋功能的控制容器,所有搜尋功能的物件都必須放入這個容器中才能運作。 • 要建立 google.search.SearchControl 物件,可以使用下列範例語法 var searchControl = new google.search.SearchControl();
26. google.search.SearchControl #3 - draw(element, GdrawOptions) • 本函式會為每個加入搜尋控制容器的搜索器進行搜尋介面繪製的動作。只有在所有搜索器都已加入搜索控制容器後,才可以呼叫此函式。 • element – HTML 區塊元素。我們可以將搜尋控制容器放置到指定的 HTML 區塊元素之中。通常 HTML 區塊元素是指 HTML 中的 <div> 元素。 • GdrawOptions – 非必填的引數。這個引數可以用來設定搜尋結果的顯示外觀。
35. google.search.SearchForm #1 • The google.search.SearchForm object is a light weight object that is designed for exactly this use case. It provides applications with a text input element, a search button, an optional clear button, as well as all standard branding. • • 要建立 google.search.SearchForm 物件,可以使用下列範例語法 var searchForm = new google.search.SearchForm(enableClear, element); • enableClear – 這個引數為 ture 時,搜索輸入欄位就會包含一個清除搜尋結果的按鈕,否則將不會有清除搜尋結果的按鈕。 • element – HTML Element 。
40. Searchers #2 • google.search.WebSearch var searcher = new google.search.WebSearch(); • google.search.LocalSearch var searcher = new google.search.LocalSearch(); • google.search.VideoSearch var searcher = new google.search.VideoSearch(); • google.search.BlogSearch var searcher = new google.search.BlogSearch();
41. Searchers #3 • google.search.NewsSearch var searcher = new google.search.NewsSearch(); • google.search.ImageSearch var searcher = new google.search.ImageSearch(); • google.search.BookSearch var searcher = new google.search.BookSearch(); • google.search.PatentSearch var searcher = new google.search.PatentSearch();
42. GResult #1 • Result objects are produced using a JSON encoding of server search requests. • 當我們透過搜尋器進行搜尋動作後,除了會在指定的網頁元素位置上顯示搜尋結果外,也會根據搜尋器的種類回傳不同的搜尋結果物件。瞭解搜尋結果物件的屬性,可以讓我們對搜尋結果物件進行更進一步的處理
43. GResult #2 • Result objects are produced using a JSON encoding of server search requests. • 當我們透過搜尋器進行搜尋動作後,除了會在指定的網頁元素位置上顯示搜尋結果外,也會根據搜尋器的種類回傳不同的搜尋結果物件。瞭解搜尋結果物件的屬性,可以讓我們對搜尋結果物件進行更進一步的處理
44. Searcher Options • When adding a searcher to the search control, the GsearcherOptionsgoogle.search.SearcherOptions object may be specified. // create a searcher options object // set up for open expansion mode // load a searcher with these options var options = new google.search.SearcherOptions(); options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN); searchControl.addSearcher(new google.search.WebSearch(), options);
45. DrawOptions Options • When asking a search control to draw, you must specify a container for the control to draw within. • In addition to this required parameter, the search control's .draw() method also accepts an optional google.search.DrawOptions object. // create a drawOptions object var drawOptions = new google.search.DrawOptions(); drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED); searchControl.draw(element, drawOptions);
47. Google Maps API Family • Google Maps has a wide array of APIs that let you embed the robust functionality and everyday usefulness of Google Maps into your own website and applications
48. Google Maps JavaScript API V3 • V3: The Solution for Maps Applications for both the Desktop and Mobile Devices • The version 3 of the Google Maps API will look similar to the existing version 2 of the Google Maps API. • Who uses Maps API: • Yelp: http://www.youtube.com/watch?v=jWmLCpE_nwg • 地圖日記 • Web Resources • http://groups.google.com/group/google-maps-js-api-v3 • http://code.google.com/apis/maps/documentation/javascript/
49. "Hello World" of Google Maps V3 #1 • Sample Code URL • http://code.google.com/apis/maps/documentation/javascript/examples/map-simple.html • Declaring Your Application as HTML5 <!DOCTYPE html> • Loading the Google Maps API <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false"> </script>
50. "Hello World" of Google Maps V3 #2 • Map DOM Elements <div id="map_canvas" style="width: 100%; height: 100%"></div> • Map Options var myLatlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; • Create instance var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
51. Geolocation • Geolocation refers to the identification of the geographic location of a user or computing device via a variety of data collecton mechanisms. • Newer browsers are starting to support the W3C Geolocation standard. // Try W3C Geolocation method (Preferred) if( navigator.geolocation ) { navigator.geolocation.getCurrentPosition( function( position ) { initialLocation = new google.maps.LatLng( position.coords.latitude,position.coords.longitude ); …… });}
52. Developing for Mobile Devices • You can detect iPhone and Android devices by inspecting the navigator.userAgent function detectBrowser() { var useragent = navigator.userAgent ; var mapdiv = document.getElementById("map_canvas"); if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) { mapdiv.style.width = '100%'; mapdiv.style.height = '100%'; } else { mapdiv.style.width = '600px'; mapdiv.style.height = '800px'; } }
53. Localization in the V3 Maps API • Language Localization <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=ja"> • Region Localization <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false®ion=GB">
54. Base objects - LatLng • LatLng is a point in geographical coordinates, latitude and longitude . var latlng = new google.maps.LatLng(60, 105); Methods Return Value Description equals(other: LatLng ) boolean Comparison function. lat() number Returns the latitude in degrees. lng() number Returns the longitude in degrees. toString() string Converts to string representation. toUrlValue() string Returns a string of the form "lat,lng" for this LatLng.
55. Base objects – LatLngBounds#1 • A LatLngBounds instance represents a rectangle in geographical coordinates . var c = new google.maps.LatLngBounds(latlngA, latlngB); Methods Return Value Description contains(latLng: LatLng ) boolean Returns true if the given lat/lng is in this bounds. equals(other: LatLngBounds ) boolean Returns true if this bounds approximately equals the given bounds. extend(point: LatLng ) LatLngBounds Extends this bounds to contain the given point. getCenter() LatLng Computes the center of this LatLngBounds getNorthEast() LatLng Returns the north-east corner of this bounds. getSouthWest() LatLng Returns the south-west corner of this bounds. intersects(other: LatLngBounds ) boolean Returns true if this bounds shares any points with this bounds. isEmpty() boolean Returns if the bounds are empty.
56. Base objects – LatLngBounds#2 toSpan() LatLng Converts the given map bounds to a lat/lng span. toString() string Converts to string. toUrlValue(precision?:number) string Returns a string of the form "lat_lo,lng_lo,lat_hi,lng_hi" for this bounds, where "lo" corresponds to the southwest corner of the bounding box, while "hi" corresponds to the northeast corner of that box. union(other: LatLngBounds ) LatLngBounds Extends this bounds to contain the union of this and the given bounds.
57. google.maps.Map • Language Localization varmap = new google.maps.Map(document.getElementById("map_canvas"), myOptions); • Some Functions setCenter(latlng: LatLng ) setMapTypeId(mapTypeId: MapTypeId ) setOptions(options: MapOptions ) setZoom(zoom:number) getMapTypeId() getZoom()
58. Google Maps Javascript API V3 Controls • Navigation control • Scale control • MapType control • You don't access or modify controls directly. Instead, you modify the map's MapOptions fields which affect the visibility and presentation of controls. You can adjust control presentation upon instantiating your map (with appropriate MapOptions) or modify a map dynamically by calling setOptions() to change the map's options.
59. The Default Control Set Control Large Screens Small Screens iPhone Android Navigation Large Pan/Zoom for sizes larger than 400x350px Small Mini-Zoom for sizes smaller than 400x350px Not present "Android" control MapType Horizontal Bar for screens larger than 320px wide Dropdown for screens smaller than 320px wide Same as Large/Small Screens Same as Large/Small Screens Scale Not present Not present Not present Not present
60. Disabling the Default UI function initialize() { var myOptions = { zoom: 4, center: new google.maps.LatLng(-33, 151), disableDefaultUI: true , mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }
61. Adding Controls to the Map { navigationControl: boolean, mapTypeControl: boolean, scaleControl: boolean } function initialize() { var myOptions = { zoom: 4, center: new google.maps.LatLng(-33, 151), navigationControl: true, mapTypeControl : true, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }
62. Control Options • Navigation control • google.maps.NavigationControlStyle.SMALL • google.maps.NavigationControlStyle.ZOOM_PAN • google.maps.NavigationControlStyle.ANDROID • google.maps.NavigationControlStyle.DEFAULT • MapType control • google.maps.MapTypeControlStyle.HORIZONTAL_BAR • google.maps.MapTypeControlStyle.DROPDOWN_MENU • google.maps.MapTypeControlStyle.DEFAULT
63. Control Positioning function initialize() { var myOptions = { zoom: 12, center: new google.maps.LatLng(-28.643387, 153.612224), mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, position: google.maps.ControlPosition.BOTTOM }, navigationControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.ZOOM_PAN, position: google.maps.ControlPosition.TOP_RIGHT }, scaleControl: true, scaleControlOptions: { position: google.maps.ControlPosition.TOP_LEFT } } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }
65. Google Maps Javascript API V3 Events #2 var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Hello World!" }); google.maps.event.addListener(marker, 'click', function() { map.setZoom(8); });
66. Google Maps Javascript API V3 Events #3 • Accessing Arguments in UI Events • MouseEvent google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); }); Properties Type Description latLng LatLng The latitude/longitude that was below the cursor when the event occurred.
67. Google Maps JavaScript API V3 Overlays #1 • Overlays are objects on the map that are tied to latitude/longitude coordinates, so they move when you drag or zoom the map. Overlays reflect objects that you "add" to the map to designate points, lines, areas, or collections of objects. • several types of overlays: • markers • polylines • overlay map types • info window • custom overlays
68. Google Maps JavaScript API V3 Overlays #2 • Adding Overlays var myLatlng = new google.maps.LatLng(-25.363882,131.044922); var myOptions = { zoom: 4, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ position: myLatlng, title:"Hello World!" }); // To add the marker to the map, call setMap(); marker.setMap(map);
69. Google Maps JavaScript API V3 Overlays #3 • Removing Overlays • http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html // Removes the overlays from the map, but keeps them in the array function clearOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } }} // Shows any overlays currently in the array function showOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(map); } }} // Deletes all markers in the array by removing references to them function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } markersArray.length = 0; }}
70. Google Maps JavaScript API V3 Overlays #4 • Markers var myLatlng = new google.maps.LatLng(-25.363882,131.044922); var myOptions = { zoom: 4, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Hello World!" });
71. Google Maps JavaScript API V3 Overlays #5 • Simple Icons var image = 'beachflag.png'; var myLatLng = new google.maps.LatLng(-33.890542, 151.274856); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); • Complex Icons var marker = new google.maps.Marker({ position: myLatLng, map: map, shadow: shadow, icon: image, shape: shape, title: beach[0], zIndex: beach[3] });
72. Google Maps JavaScript API V3 Overlays #6 • Polylines • A polyline supports the following stroke styles: • strokeColor • strokeOpacity • strokeWeight var flightPlanCoordinates = [ new google.maps.LatLng(37.772323, -122.214897), new google.maps.LatLng(21.291982, -157.821856), new google.maps.LatLng(-18.142599, 178.431), new google.maps.LatLng(-27.46758, 153.027892) ]; var flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2 }); flightPath.setMap(map);
73. Google Maps JavaScript API V3 Overlays #7 • Polygons • A polygons supports the ploylines stroke styles and fill styles: • fillColor • fillOpacity var triangleCoords = [ new google.maps.LatLng(25.774252, -80.190262), new google.maps.LatLng(18.466465, -66.118292), new google.maps.LatLng(32.321384, -64.75737), new google.maps.LatLng(25.774252, -80.190262) ]; // Construct the polygon // Note that we don't specify an array or arrays, but instead just // a simple array of LatLngs in the paths property bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35 }); bermudaTriangle.setMap(map);
74. Google Maps JavaScript API V3 Overlays #8 • Ground var oldmap = new google.maps.GroundOverlay( "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", imageBounds); oldmap.setMap(map);
75. Google Maps JavaScript API V3 Overlays #9 • InfoWindows • Methods • InfoWindow options • content • pixelOffset • position • maxWidth Methods Return Value Description close() None Closes this InfoWindow getContent() string|Node getPosition() LatLng getZIndex() number open(map: Map | StreetViewPanorama , anchor?: MVCObject ) None setContent(content:string|Node) None
76. Google Maps JavaScript API V3 Overlays #10 • KML and GeoRSS Layers • The Google Maps API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file.
77. Google Maps JavaScript API V3 Overlays #11 • The Traffic Layer • The Bicycling Layer • http://gmaps-samples.googlecode.com/svn/trunk/mapcoverage_filtered.html
78.
79.
80. Google Maps JavaScript API V3 Services #3 • Geocoding function codeAddress() { var address = document.getElementById("address").value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert("Geocode was not successful for the following reason: " + status); } }); }
81. Google Maps JavaScript API V3 Services #4 • Reverse Geocoding function codeLatLng() { var input = document.getElementById("latlng").value; var latlngStr = input.split(",",2); var lat = parseFloat(latlngStr[0]); var lng = parseFloat(latlngStr[1]); var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { map.setZoom(11); marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); } } else { alert("Geocoder failed due to: " + status); } }); }
82. Google Maps JavaScript API V3 Services #5 • The DirectionsRequest object literal contains the following fields: { origin: LatLng | String, destination: LatLng | String, travelMode: DirectionsTravelMode, unitSystem: DirectionsUnitSystem, waypoints[]: DirectionsWaypoint, optimizeWaypoints: Boolean, provideRouteAlternatives: Boolean, avoidHighways: Boolean, avoidTolls: Boolean region: String }
83. Google Maps JavaScript API V3 Services #6 • Street View var fenway = new google.maps.LatLng(42.345573,-71.098326); var mapOptions = { center: fenway, zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP, streetViewControl: true }; var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
86. Google Chart Tools • The Google Chart Tools enable adding live charts to any web page. • The advantages of the Google Chart Tools • A rich gallery of visualizations provided as: • Image charts - using a simple URL request to a Google chart server • Interactive charts - using a Google developed JavaScript library • Can read live data from a variety of data sources • Simple to use and free
89. Google Chart Tools – Image Charts #3 • The Google Chart API returns a chart image in response to a URL GET or POST request. http://chart.apis.google.com/chart?cht=<chart_type>&chd=<chart_data>&chs=<chart_size>&...additional_parameters ... OR <form action='http://chart.apis.google.com/chart' method='POST'> <input type="hidden" name="cht" value="lc" /> <input type="hidden" name="chtt" value="This is | my chart" /> <input type='hidden' name='chs' value='600x200' /> <input type="hidden" name="chxt" value="x,y" /> <input type='hidden' name='chd' value='t:40,20,50,20,100'/> <input type="submit" /> </form>
91. Google Chart Tools – Image Charts #5 • Chart Play Ground • http://code.google.com/apis/chart/docs/chart_playground.html
92. Google Chart Tools – Interactive Charts #1 • The key steps for embedding a visualization in your page • Add a <div> to your page <!--Div that will hold the pie chart--> <div id="my_chart_div"></div> • Load your libraries <!--Load the AJAX API--> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> // Load the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['piechart']}); // Load multiple Google packages: // google.load('visualization', '1', {'packages':['piechart', 'table', 'linechart']}); <script>
93. Google Chart Tools – Interactive Charts #2 • The key steps for embedding a visualization in your page • Prepare your data var data = new google.visualization.DataTable(); // Declare columns and rows. data.addColumn('string', 'Task'); // Column 0 is type string and has label "Task". data.addColumn('number', 'Hours per Day'); // Column 1 is type number and has label "Hours per Day". // Add data. data.addRows([ ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); • Create an instance of your visualization • Draw your visualization
94. Google Chart Tools – Interactive Charts #3 • The key steps for embedding a visualization in your page • Create an instance of your visualization var chart = new google.visualization.PieChart(document.getElementById('chart_div')); • Draw your visualization chart.draw(data, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'});
95. Google Chart Tools – Interactive Charts #4 • Code Example • http://code.google.com/apis/visualization/documentation/examples.html
97. Google Data Protocol • The Google Data Protocol provides a secure means for external developers to write new applications that let end users access and update the data stored by many Google products. • External developers can use the Google Data Protocol directly, or they can use any of the supported programming languages provided by the client libraries. • The protocol currently supports two primary modes of access: • AtomPub • JSON • http://code.google.com/apis/gdata/
98. Google Data Protocol – API Directory • http://code.google.com/apis/gdata/docs/directory.html
99. Authentication in the Google Data Protocol • AuthSub • Oauth • http://googlecodesamples.com/oauth_playground/index.php • ClientLogin • Gadgets
100. Google Data Protocol – For Example • Google Calendar Data API • Retrieving all calendars • https://www.google.com/calendar/feeds/default/allcalendars/full • Picasa Web Albums Data API • Requesting a list of albums • http://picasaweb.google.com/data/feed/api/user/ userID